/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

namespace DNNContentBuilder.UserControls.FieldControls
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Collections;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using System.Xml;

	/// <summary>
	///		Summary description for options.
	/// </summary>
	public class FieldType : System.Web.UI.UserControl
	{
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/FieldType";

		public event EventHandler RebuildFieldListEvent;
		
		protected System.Web.UI.WebControls.Label ControlTypeId;

		private DNNContentBuilder.ControlTypeController ctController = new ControlTypeController();

		protected DotNetNuke.UI.UserControls.UrlControl URLControl1;
		protected System.Web.UI.UserControl CommonDef1;
		protected System.Web.UI.WebControls.DropDownList ddControlTypes;
		protected System.Web.UI.HtmlControls.HtmlTable Table1;
		protected System.Web.UI.WebControls.Panel pnDynamicControl;
		protected System.Web.UI.WebControls.LinkButton btConfig;
		private DNNContentBuilder.ControlTypeInfo ctInfo = new ControlTypeInfo();
		
		private System.Web.UI.UserControl myHeader;
		private System.Web.UI.UserControl myControl;
		protected System.Web.UI.WebControls.LinkButton btUpdateProperties;
		private System.Web.UI.UserControl myFooter;

		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here

			this.btConfig.Text = Commons.GetLocalizedString("button_Config", resource);
			this.btUpdateProperties.Text = Commons.GetLocalizedString("button_Update", resource);
			this.ControlTypeId.Text = Commons.GetLocalizedString("label_ControlType", resource);

			int actualIndex = ddControlTypes.SelectedIndex;

			this.ddControlTypes.DataSource = (ArrayList)ctController.GetAllControlType();
			this.ddControlTypes.DataTextField = "Title";
			this.ddControlTypes.DataValueField = "ControlPath";
			this.ddControlTypes.DataBind();

			ddControlTypes.SelectedIndex = actualIndex;

		}


		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);

			if ((string)Session["myHeader"] != null) 
			{
				myHeader = (System.Web.UI.UserControl)Page.LoadControl("DesktopModules\\DNNContentBuilder\\UserControls\\FieldControls\\CommonDef.ascx");
				myHeader.ID = "myDynamicFormHeader";
				pnDynamicControl.Controls.Add(myHeader);

				myControl = (System.Web.UI.UserControl)Page.LoadControl((string)Session["myControl"]);
				myControl.ID = "myDynamicFormControl";
				pnDynamicControl.Controls.Add(myControl);

				myFooter = (System.Web.UI.UserControl)Page.LoadControl("DesktopModules\\DNNContentBuilder\\UserControls\\FieldControls\\CommonEndDef.ascx");
				myFooter.ID = "myDynamicFormFooter";
				pnDynamicControl.Controls.Add(myFooter);
			
			} 
			else 
			{
				this.pnDynamicControl.Visible = false;
			}
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btConfig.Click += new System.EventHandler(this.btConfig_Click);
			this.btUpdateProperties.Click += new System.EventHandler(this.btUpdateProperties_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		public void SetSelected(string selSelected) 
		{
			this.ddControlTypes.SelectedValue = selSelected;
		}

		private void btConfig_Click(object sender, System.EventArgs e)
		{
			if (ddControlTypes.SelectedValue.IndexOf(".PK") > -1) 
			{
				configPK();
				return;
			}

			this.btUpdateProperties.Visible = true;

			Session.Remove("myHeader");
			Session.Remove("myControl");
			Session.Remove("myFooter");

			pnDynamicControl.Controls.Clear();

			// setting btSelected

			System.Web.UI.Control lastButton = Page.FindControl((string)Session["lastButton"]);

			XmlDocument xmlDoc = new XmlDocument();

			xmlDoc.LoadXml(((ImageButton)lastButton).CommandArgument);

			XmlNode tempNode;

			tempNode = xmlDoc.SelectSingleNode("//UniqueId");
			tempNode.InnerText = ((ImageButton)lastButton).UniqueID;

			tempNode = xmlDoc.SelectSingleNode("//SourceField");

			if (tempNode.InnerText == "") 
			{
				tempNode.InnerText = ((ImageButton)lastButton).CommandName;
			}

			tempNode = xmlDoc.SelectSingleNode("//ControlPath");
			tempNode.InnerText = ddControlTypes.SelectedValue;

			((ImageButton)lastButton).CommandArgument = xmlDoc.OuterXml;

			//Form Header
			myHeader = (System.Web.UI.UserControl)Page.LoadControl("DesktopModules\\DNNContentBuilder\\UserControls\\FieldControls\\CommonDef.ascx");
			myHeader.ID = "myDynamicFormHeader";

			pnDynamicControl.Controls.Add(myHeader);

			Session.Add("myHeader", myHeader.UniqueID);

			//Form Extended
			myControl = (System.Web.UI.UserControl)Page.LoadControl(ddControlTypes.SelectedValue);

			myControl.ID = "myDynamicFormControl";

			pnDynamicControl.Controls.Add(myControl);

			Session.Add("myControl", this.ddControlTypes.SelectedValue);

			ArgumentValidator.AssertExpectedType(myHeader, typeof(IFormletDef), "ERR_INVALID_FORMLET_DEF");
			
			// Set Regular properties on the header control
			((IFormletDef)myHeader).SetXml(((ImageButton)lastButton).CommandArgument);

			ArgumentValidator.AssertExpectedType(myControl, typeof(IFormletDef), "ERR_INVALID_FORMLET_DEF");

			// Set Extended Properties on the custom control itself
			((IFormletDef)myControl).SetXml(((ImageButton)lastButton).CommandArgument);

			// Form Footer
			myFooter = (System.Web.UI.UserControl)Page.LoadControl("DesktopModules\\DNNContentBuilder\\UserControls\\FieldControls\\CommonEndDef.ascx");

			myFooter.ID = "myDynamicFormFooter";

			Session.Add("myFooter", myFooter.UniqueID);

			pnDynamicControl.Controls.Add(myFooter);

			// Show all
			pnDynamicControl.Visible = true;

			this.btUpdateProperties.Visible = true;
		}

		private void configPK () 
		{
			System.Web.UI.Control lastButton = Page.FindControl((string)Session["lastButton"]);

			XmlDocument xmlDoc = new XmlDocument();
			XmlDocument xmlDoc2 = new XmlDocument();
			xmlDoc.Load(System.Web.HttpContext.Current.Server.MapPath("~\\DesktopModules\\DNNContentBuilder\\UserControls\\FieldControls\\XML\\RegularProperties.xml"));
			xmlDoc2.Load(System.Web.HttpContext.Current.Server.MapPath("~\\DesktopModules\\DNNContentBuilder\\UserControls\\FieldControls\\XML\\PrimaryKey.xml"));

			XmlNode extNode = xmlDoc.SelectSingleNode("//ExtendedProperties");

			extNode.InnerXml = xmlDoc2.InnerXml;

			XmlNode tempNode;

			tempNode = xmlDoc.SelectSingleNode("//UniqueId");
			tempNode.InnerText = "GUID";

			tempNode = xmlDoc.SelectSingleNode("//SourceField");
			tempNode.InnerText = ((ImageButton)lastButton).CommandName;

			tempNode = xmlDoc.SelectSingleNode("//FieldType");
			tempNode.InnerText = "GUID";
			
			tempNode = xmlDoc.SelectSingleNode("//ControlPath");
			tempNode.InnerText = ".PK";

			tempNode = xmlDoc.SelectSingleNode("//FriendlyName");
			tempNode.InnerText = ((ImageButton)lastButton).CommandName.Substring(0,((ImageButton)lastButton).CommandName.IndexOf(".")) + ".PK";

			tempNode = xmlDoc.SelectSingleNode("//CssClass");
			tempNode.InnerText = "";

			tempNode = xmlDoc.SelectSingleNode("//Search");
			tempNode.InnerText = "False";

			tempNode = xmlDoc.SelectSingleNode("//Tooltip");
			tempNode.InnerText = ((ImageButton)lastButton).CommandName.Substring(0,((ImageButton)lastButton).CommandName.IndexOf(".")) + ".PK";

			tempNode = xmlDoc.SelectSingleNode("//Required");
			tempNode.InnerText = "True";

			((ImageButton)lastButton).CommandArgument = xmlDoc.InnerXml;

			ArrayList myList = (ArrayList)Session["fieldList"];

			foreach (DNNContentBuilder.FieldInfo field in myList) 
			{
				if (field.name == ((ImageButton)lastButton).CommandName) 
				{
					field.columnProperties = ((ImageButton)lastButton).CommandArgument;
					break;
				}
			}

			Session.Add("fieldList", myList);

			Session.Remove("myHeader");
			Session.Remove("myControl");
			Session.Remove("myFooter");

			pnDynamicControl.Visible = false;

		}

		private void btUpdateProperties_Click(object sender, System.EventArgs e)
		{
			System.Web.UI.Control lastButton = Page.FindControl((string)Session["lastButton"]);

			ArgumentValidator.AssertExpectedType(myHeader, typeof(IFormletDef), "ERR_INVALID_FORMLET_DEF");

			//Get Regular properties
			((IFormletDef)myHeader).GetXml(((ImageButton)lastButton).CommandArgument);

			ArgumentValidator.AssertExpectedType(myControl, typeof(IFormletDef), "ERR_INVALID_FORMLET_DEF");

			//Get Extended Properties
			((IFormletDef)myControl).GetXml(((ImageButton)lastButton).CommandArgument);

			ArrayList myList = (ArrayList)Session["fieldList"];

			foreach (DNNContentBuilder.FieldInfo field in myList) 
			{
				if (field.name == ((ImageButton)lastButton).CommandName) 
				{
					field.columnProperties = ((ImageButton)lastButton).CommandArgument;
					
					XmlDocument xmlDoc = new XmlDocument();
					
					xmlDoc.LoadXml(field.columnProperties);
					
					XmlNode tempNode = xmlDoc.SelectSingleNode("//ExtendedProperties");
					
					field.controlTypeName = tempNode.FirstChild.Name;
					
					break;
				}
			}
			
			Session.Add("fieldList", myList);

			Session.Remove("myHeader");
			Session.Remove("myControl");
			Session.Remove("myFooter");
			
			pnDynamicControl.Visible = false;

			btUpdateProperties.Visible = false;

			RebuildFieldListEvent(myList, new System.EventArgs()); // or whatever args you want
		}
	}
}
